import React, { useState, useEffect } from "react";
import { Popup, List, Image, Toast } from "antd-mobile";
import { AMapKey, getCityInfo } from "../../utils/index";

import axios from "axios";
import "./index.less";

import HeaderTitle from "../../components/HeaderTitle";

const url = "http://192.168.9.228:9999";

export default function Map() {
  const [houseList, setHouseList] = useState([]);

  // 弹出框的展示和隐藏
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const cityInfo = getCityInfo("HKZF_CITY");

    (async () => {
      const AMap = await AMapKey;

      const map = new AMap.Map("container", { zoom: 10, isHotspot: true });

      initMap();

      // 创建地图实例
      function initMap() {
        try {
          AMap.plugin(["AMap.Geocoder", "AMap.ToolBar", "AMap.Scale"], () => {
            let geocoder = new AMap.Geocoder({ city: "全国" });

            // 比例尺
            var scale = new AMap.Scale();
            map.addControl(scale);
            //加载工具条
            let tool = new AMap.ToolBar();
            map.addControl(tool);

            geocoder.getLocation(cityInfo.label, (status, result) => {
              if (status === "complete" && result.geocodes.length) {
                let lnglat = result.geocodes[0].location;
                map.setCenter(lnglat);
                map.setZoom(10);
                renderOverlays(cityInfo.value);
              }
            });
          });

          map.on("click", () => {
            setVisible((flag) => (flag = false));
          });
          map.on("dblclick", () => {
            setVisible((flag) => (flag = false));
          });
        } catch (e) {
          console.log(e);
        }
      }

      // 渲染覆盖物入口
      async function renderOverlays(id) {
        try {
          Toast.show({
            icon: "loading",
            content: "加载中…",
            duration: 0,
          });
          const { data } = await axios.get(url + `/area/map?id=${id}`);

          Toast.clear();

          let { nextZoom, type } = getTypeAndZoom();

          data.body.forEach((item) => {
            createOverlays(item, nextZoom, type);
          });
        } catch (e) {
          console.log(e);
          Toast.clear();
        }
      }

      // 计算类型和缩放级别
      function getTypeAndZoom() {
        let zoom = map.getZoom(); // 精确放大级别
        let nextZoom, type;
        if (zoom >= 10 && zoom < 11) {
          nextZoom = 13; // 区
          type = "circle";
        } else if (zoom >= 11 && zoom < 14) {
          nextZoom = 15; // 镇
          type = "circle";
        } else if (zoom >= 14 && zoom < 20) {
          type = "rect"; // 小区
        }
        return { nextZoom, type };
      }

      // 创建覆盖物
      function createOverlays(data, zoom, type) {
        const {
          coord: { longitude, latitude },
          value,
          label,
          count,
        } = data;

        const areaPoint = new AMap.LngLat(longitude, latitude);

        if (type === "circle") {
          // 区、镇
          createCircle(areaPoint, value, label, count, zoom);
        } else {
          // 小区
          createRect(areaPoint, value, label, count);
        }
      }

      // 创建区、镇覆盖物
      function createCircle(areaPoint, value, label, count, zoom) {
        let circle = new AMap.Text({
          anchor: "center",
          cursor: "pointer",
          bubble: false,
          position: areaPoint,
        });
        circle.id = value;
        circle.setContent(`
                <div class="bubble">
                  <p class="name">${label}</p>
                  <p class="count">${count}套</p>
                </div>
              `);
        circle.on("click", () => {
          // 放大地图
          map.setZoomAndCenter(zoom, areaPoint);
          // 清除当前覆盖物信息
          map.clearMap();

          renderOverlays(circle.id);
        });
        map.add(circle);
      }

      // 创建小区覆盖物
      function createRect(areaPoint, value, label, count) {
        let rect = new AMap.Text({
          anchor: "center",
          cursor: "pointer",
          position: areaPoint,
        });
        rect.id = value;
        rect.setContent(`
                <div class="rect">
                  <p class="name name-label">${label}</p>
                  <p class="count">${count}套</p>
                </div>
              `);
        rect.on("click", (e) => {
          getHouseList(rect.id);
          setVisible(true);
          let target = e.originEvent.changedTouches[0];
          // 点击小区的时候，移动地图
          map.panBy(
            window.innerWidth / 2 - target.clientX,
            (window.innerHeight - window.innerHeight / 2) / 2 - target.clientY
          );
        });
        map.add(rect);
      }

      // 获取小区房源
      async function getHouseList(id) {
        try {
          Toast.show({
            icon: "loading",
            content: "加载中…",
            duration: 0,
          });
          const { data } = await axios.get(`${url}/houses?cityId=${id}`);
          Toast.clear();
          setHouseList(data.body.list);
        } catch (e) {
          console.log(e);
          Toast.clear();
        }
      }
    })();
  }, []);

  function renderHouseList() {
    return (
      <Popup className="house-pop" mask={false} visible={visible} destroyOnClose>
        <HeaderTitle className="header" title="房屋列表" more="更多房源" />
        <div className="house-list">
          <List>
            {houseList.map((item) => (
              <List.Item
                key={item.houseCode}
                prefix={<Image src={url + item.houseImg} fit="cover" width={80} height={60} />}
                onClick={() => houseClick(item)}
              >
                <div className="house-title">{item.title}</div>
                <div className="house-desc">{item.desc}</div>
                <div className="house-tag">
                  {item.tags.map((tag, index) => {
                    const tagClass = "tag" + (index + 1);
                    return (
                      <span className={["house-tags", tagClass].join(" ")} key={tag}>
                        {tag}
                      </span>
                    );
                  })}
                </div>
                <div className="house-price">
                  <span className="priceNum">{item.price}</span> 元/月
                </div>
              </List.Item>
            ))}
          </List>
        </div>
      </Popup>
    );
  }

  // 小区房源点击事件
  function houseClick(data) {
    console.log(data);
  }

  return (
    <div className="map">
      {/* 地图 */}
      <div id="container"></div>

      {/* 弹窗 */}
      {renderHouseList()}
    </div>
  );
}
